/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package javaapplication1;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;


/**
 *
 * @author Oren
 */
public class RunProgram implements Runnable {
    private FileReader fr ;
    private Robot robot ;
    int endtime;
    private int PC, LC  ;
    private ProgramCommandExecutor PCE;
    private String name;
    private BufferedReader br ;
    private Boxes bx;
    private String line ;

    public RunProgram(Robot rbt,String filename,Boxes boxs) throws FileNotFoundException
    {
        try {
            fr = new FileReader(filename);
            name = filename;
            robot = rbt;
            // Program Counter (time)
            PC = 0;
            // Line Counter (next command)
            LC = 1;
            endtime = 0;
            br = new BufferedReader(fr);
            bx = boxs;
            if (br.ready()) {
                line = br.readLine();
            }
            PCE = new ProgramCommandExecutor();
        } catch (IOException ex) {
            Logger.getLogger(RunProgram.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public synchronized void  run()
    {
        try {
            
            String time = null;       
            if (line!=null)
                 time = getFirstWord(line);

            // check if there is another line
            while (line != null) {
                if (Integer.parseInt(time) == PC) {
                    System.out.println("\t" + name + " on " + robot.getName() + " " + line);
                    // run the command
                    PCE.runCommand(line,robot,bx);
                    line = br.readLine();
                    if (line!=null)
                        time = getFirstWord(line);
                    LC ++;
                }
                robot.act();
                PC++; // incerment program coutnter

                Thread.sleep(1000); // wait one sec before doing the next line
                // the time period has ended 
                if (PC == (endtime+1))

                    break;

            }
        } catch (InterruptedException ex) {
            Logger.getLogger(RunProgram.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(RunProgram.class.getName()).log(Level.SEVERE, null, ex);
        }
   }
    

    public String getFirstWord(String cmd)
    {
        String words[]= cmd.split(" ");
        return words[0];
    }

    public void setTime(int time)
    {
        endtime = endtime + time;
    }

    public int getTime()
    {
        return PC;
    }


}
